package com.qjs.smterp.utils;

public class DbTextUtil {

    public static String wrapWordByCommas(String s) {
	return "'" + s + "'";
    }

    public static String formQueryPair(String source, String value) {
	if (value.equals("%")) {
	    source += " IS NOT NULL";
	} else {
	    source += getOperationType(value) + wrapWordByCommas(value);
	}
	return source;
    }

    public static String formQueryPair2(String source, String value) {
	if (source.equals("hpan")) {
	    if (findLikeSymbol(value)) {
		value = wrapWordByCommas(value);
		return source + " LIKE " + value;
	    }
	    value = wrapWordByCommas(value);
	}
	return " A." + source + " = " + value;
    }

    public static String getOperationType(String value) {
	return ((value != null && findLikeSymbol(value)) ? " LIKE " : " = ");
    }

    public static boolean findLikeSymbol(String s) {
	int percent = s.indexOf('%');
	int space = s.indexOf('_');

	return ((percent > -1) || (space > -1));
    }

    public static String correctField(String field) {
	int index = field.indexOf('(');

	if (index != -1) {
	    field = field.substring(0, index);
	}

	return field;
    }

    public static String parseNumericTime(int time) throws Exception {
	String ret = null;
	if (time < 0) {
	    throw (new Exception(
		    "Illigal argument format, must be positive or zero"));
	} else {
	    ret = parseNumericTime(String.valueOf(time));
	}
	return (ret);
    }

    public static String parseNumericTime(String time) throws Exception {
	String ret = null;
	if (null != time) {
	    if (time.indexOf("-") >= 0) {
		throw (new Exception(
			"Illigal argument format, must be positive or zero"));
	    } else {
		int length = time.length();
		if (length > 6) {
		    throw (new Exception(
			    "Illigal argument format. Must be 6 digits or less."));
		} else {
		    // right append with 0 to 6 digits string
		    String s = "";
		    for (int i = 0; i < 6 - length; i++) {
			s = "0" + s;
		    }
		    s += time;
		    // divide 6 digits string into 3 parts: hh, mm, ss
		    ret = s.substring(0, 2) + ":" + s.substring(2, 4) + ":"
			    + s.substring(4);
		}
	    }
	}
	return ret;
    }
}
